<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '测试数据管理',
  },
}
</route>
<template>
  <view class="test-data-page" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="i-fa-solid:arrow-left"></text>
      </view>
      <view class="navbar-title">测试数据管理</view>
      <view class="navbar-right"></view>
    </view>

    <!-- 操作区域 -->
    <view class="p-4">
      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">生成任务测试数据</text>
        <view class="flex items-center mb-4">
          <view class="flex-1">
            <slider :value="dataCount" :min="5" :max="50" :step="1" show-value @change="onCountChange" />
          </view>
          <text class="ml-2">{{ dataCount }}条</text>
        </view>
        <button class="primary-btn" @click="generateData">开始生成</button>
      </view>

      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">一键生成所有测试数据</text>
        <view class="mb-4">
          <text class="text-gray-600">将生成任务、财务记录、番茄钟记录和笔记等所有类型的测试数据</text>
        </view>
        <button class="accent-btn" @click="generateAllData">生成所有测试数据</button>
      </view>

      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">测试数据管理</text>
        <view class="flex space-x-2">
          <button class="flex-1 secondary-btn" @click="clearTestData">清空测试数据</button>
          <button class="flex-1 secondary-btn" @click="reloadData">刷新数据</button>
        </view>
      </view>

      <!-- 当前数据统计 -->
      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">当前数据统计</text>
        <view v-if="loading" class="flex justify-center py-4">
          <view class="loading-spinner"></view>
        </view>
        <view v-else class="space-y-2">
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">总任务数量</text>
            <text class="font-semibold">{{ stats.tasks.total }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">已完成任务</text>
            <text class="font-semibold">{{ stats.tasks.completed }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">今日任务</text>
            <text class="font-semibold">{{ stats.tasks.today }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">财务记录</text>
            <text class="font-semibold">{{ stats.finances.total }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">番茄钟记录</text>
            <text class="font-semibold">{{ stats.pomodoros.total }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">笔记数量</text>
            <text class="font-semibold">{{ stats.notes.total }}</text>
          </view>
        </view>
      </view>

      <!-- 任务按分类统计 -->
      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">任务按分类统计</text>
        <view v-if="loading" class="flex justify-center py-4">
          <view class="loading-spinner"></view>
        </view>
        <view v-else>
          <view v-for="(count, category) in stats.tasks.categories" :key="category" class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">{{ category }}</text>
            <text class="font-semibold">{{ count }}</text>
          </view>
          <view v-if="Object.keys(stats.tasks.categories).length === 0" class="py-2 text-center text-gray-500">
            暂无数据
          </view>
        </view>
      </view>

      <!-- 财务记录统计 -->
      <view class="bg-white rounded-lg shadow p-4 mb-4">
        <text class="text-lg font-bold mb-2 block">财务记录统计</text>
        <view v-if="loading" class="flex justify-center py-4">
          <view class="loading-spinner"></view>
        </view>
        <view v-else class="space-y-2">
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">收入总计</text>
            <text class="font-semibold text-green-600">¥{{ stats.finances.income.toFixed(2) }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">支出总计</text>
            <text class="font-semibold text-red-600">¥{{ stats.finances.expense.toFixed(2) }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">结余</text>
            <text :class="['font-semibold', stats.finances.balance >= 0 ? 'text-green-600' : 'text-red-600']">
              ¥{{ stats.finances.balance.toFixed(2) }}
            </text>
          </view>
        </view>
      </view>

      <!-- 番茄钟记录统计 -->
      <view class="bg-white rounded-lg shadow p-4">
        <text class="text-lg font-bold mb-2 block">番茄钟统计</text>
        <view v-if="loading" class="flex justify-center py-4">
          <view class="loading-spinner"></view>
        </view>
        <view v-else class="space-y-2">
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">工作番茄数</text>
            <text class="font-semibold">{{ stats.pomodoros.work }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">已完成番茄</text>
            <text class="font-semibold">{{ stats.pomodoros.completed }}</text>
          </view>
          <view class="flex justify-between py-2 border-b border-gray-100">
            <text class="text-gray-600">总专注时间</text>
            <text class="font-semibold">{{ formatDuration(stats.pomodoros.totalDuration) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载中遮罩 -->
    <view class="loading-overlay" v-if="globalLoading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">{{ loadingText }}</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TestDataPage',
})

import { dataGenerator } from '@/services/data-generator'
import { taskService } from '@/services/task-service'
import type { Task } from '@/services/task-service'
import { dbService, TABLES } from '@/services/database'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 数据生成数量
const dataCount = ref(10)

// 加载状态
const loading = ref(false)
const globalLoading = ref(false)
const loadingText = ref('加载中...')

// 数据统计
const stats = ref({
  tasks: {
    total: 0,
    completed: 0,
    today: 0,
    highPriority: 0,
    categories: {} as Record<string, number>
  },
  finances: {
    total: 0,
    income: 0,
    expense: 0,
    balance: 0
  },
  pomodoros: {
    total: 0,
    work: 0,
    completed: 0,
    totalDuration: 0
  },
  notes: {
    total: 0
  }
})

// 滑块值变化
const onCountChange = (e: any) => {
  dataCount.value = e.detail.value
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 生成测试数据
const generateData = async () => {
  try {
    showGlobalLoading(`正在生成${dataCount.value}条测试数据...`)
    
    // #ifdef APP-PLUS || H5
    const success = await dataGenerator.generateTasks(dataCount.value)
    // #endif
    
    // #ifndef APP-PLUS || H5
    // 在其他平台上模拟成功
    const success = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    // #endif
    
    hideGlobalLoading()
    
    if (success) {
      uni.showToast({
        title: `成功生成${dataCount.value}条测试数据`,
        icon: 'success'
      })
      // 刷新统计数据
      loadStatistics()
    } else {
      throw new Error('生成测试数据失败')
    }
  } catch (error) {
    hideGlobalLoading()
    uni.showModal({
      title: '生成失败',
      content: error.message || '生成测试数据过程中发生错误',
      showCancel: false
    })
  }
}

// 生成所有测试数据
const generateAllData = async () => {
  uni.showModal({
    title: '生成所有测试数据',
    content: '确定要生成所有类型的测试数据吗？这将包括任务、财务记录、番茄钟记录和笔记。',
    success: async (res) => {
      if (res.confirm) {
        try {
          showGlobalLoading('正在生成所有测试数据...')
          
          // #ifdef APP-PLUS || H5
          const success = await dataGenerator.generateAllTestData()
          // #endif
          
          // #ifndef APP-PLUS || H5
          // 在其他平台上模拟成功
          const success = true
          await new Promise(resolve => setTimeout(resolve, 1500))
          // #endif
          
          hideGlobalLoading()
          
          if (success) {
            uni.showToast({
              title: '成功生成所有测试数据',
              icon: 'success'
            })
            // 刷新统计数据
            loadStatistics()
          } else {
            throw new Error('生成所有测试数据失败')
          }
        } catch (error) {
          hideGlobalLoading()
          uni.showModal({
            title: '生成失败',
            content: error.message || '生成测试数据过程中发生错误',
            showCancel: false
          })
        }
      }
    }
  })
}

// 清空测试数据
const clearTestData = async () => {
  uni.showModal({
    title: '警告',
    content: '确定要清空所有测试数据吗？此操作不可恢复！',
    confirmColor: '#FF0000',
    success: async (res) => {
      if (res.confirm) {
        try {
          showGlobalLoading('正在清空测试数据...')
          
          // #ifdef APP-PLUS || H5
          const success = await dataGenerator.clearAllTestData()
          // #endif
          
          // #ifndef APP-PLUS || H5
          // 在其他平台上模拟成功
          const success = true
          await new Promise(resolve => setTimeout(resolve, 1000))
          // #endif
          
          hideGlobalLoading()
          
          if (success) {
            uni.showToast({
              title: '已清空所有测试数据',
              icon: 'success'
            })
            // 刷新统计数据
            loadStatistics()
          } else {
            throw new Error('清空测试数据失败')
          }
        } catch (error) {
          hideGlobalLoading()
          uni.showModal({
            title: '操作失败',
            content: error.message || '清空数据过程中发生错误',
            showCancel: false
          })
        }
      }
    }
  })
}

// 重新加载数据
const reloadData = () => {
  loadStatistics()
}

// 加载数据统计
const loadStatistics = async () => {
  loading.value = true
  try {    
    // 确保数据库已初始化
    if (!dbService.isInitialized()) {
      console.warn('数据库尚未初始化，操作可能失败');
      // 可以考虑等待一段时间或提示用户
      return;
    }
    
    // #ifdef APP-PLUS || H5
    // 获取今天的日期
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const todayStr = today.toISOString().split('T')[0]
    
    // 统计任务数据
    const allTasks = await taskService.getAllTasks()
    const completedTasks = allTasks.filter(task => task.completed)
    const todayTasks = allTasks.filter(task => task.date === todayStr)
    const highPriorityTasks = allTasks.filter(task => task.priority === 'high')
    
    // 按分类统计任务
    const taskCategories: Record<string, number> = {}
    allTasks.forEach(task => {
      const category = task.category || '未分类'
      if (!taskCategories[category]) {
        taskCategories[category] = 0
      }
      taskCategories[category]++
    })
    
    // 统计财务记录
    const financialRecords = await dbService.query(`SELECT * FROM ${TABLES.FINANCIAL_RECORDS}`)
    let totalIncome = 0
    let totalExpense = 0
    
    financialRecords.forEach(record => {
      if (record.type === '收入') {
        totalIncome += parseFloat(record.amount)
      } else if (record.type === '支出') {
        totalExpense += parseFloat(record.amount)
      }
    })
    
    // 统计番茄钟记录
    const pomodoroRecords = await dbService.query(`SELECT * FROM ${TABLES.POMODOROS}`)
    const workPomodoros = pomodoroRecords.filter(record => record.type === 'work')
    const completedPomodoros = pomodoroRecords.filter(record => record.completed === 1)
    let totalDuration = 0
    
    // 计算总专注时间
    workPomodoros.forEach(record => {
      if (record.completed === 1) {
        totalDuration += parseInt(record.duration)
      }
    })
    
    // 统计笔记
    const notes = await dbService.query(`SELECT * FROM ${TABLES.NOTES}`)
    
    // 更新统计数据
    stats.value = {
      tasks: {
        total: allTasks.length,
        completed: completedTasks.length,
        today: todayTasks.length,
        highPriority: highPriorityTasks.length,
        categories: taskCategories
      },
      finances: {
        total: financialRecords.length,
        income: totalIncome,
        expense: totalExpense,
        balance: totalIncome - totalExpense
      },
      pomodoros: {
        total: pomodoroRecords.length,
        work: workPomodoros.length,
        completed: completedPomodoros.length,
        totalDuration
      },
      notes: {
        total: notes.length
      }
    }
    // #endif
    
    // #ifndef APP-PLUS || H5
    // 在其他平台上使用模拟数据
    stats.value = {
      tasks: {
        total: 0,
        completed: 0,
        today: 0,
        highPriority: 0,
        categories: {}
      },
      finances: {
        total: 0,
        income: 0,
        expense: 0,
        balance: 0
      },
      pomodoros: {
        total: 0,
        work: 0,
        completed: 0,
        totalDuration: 0
      },
      notes: {
        total: 0
      }
    }
    // #endif
  } catch (error) {
    console.error('加载统计数据失败:', error)
    uni.showToast({
      title: '加载统计失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 显示全局加载
const showGlobalLoading = (text: string = '加载中...') => {
  loadingText.value = text
  globalLoading.value = true
}

// 隐藏全局加载
const hideGlobalLoading = () => {
  globalLoading.value = false
}

// 页面加载时获取统计数据
onLoad(() => {
  loadStatistics()
})
</script>

<style lang="scss">
.test-data-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f2f2f7;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #e5e5ea;
}

.navbar-left {
  display: flex;
  align-items: center;
  width: 60px;
  font-size: 16px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: 600;
}

.navbar-right {
  width: 60px;
  text-align: right;
}

.primary-btn {
  width: 100%;
  padding: 12px;
  background-color: #007aff;
  color: white;
  border-radius: 8px;
  font-size: 16px;
  text-align: center;
}

.secondary-btn {
  padding: 12px;
  background-color: #f2f2f7;
  color: #007aff;
  border: 1px solid #007aff;
  border-radius: 8px;
  font-size: 16px;
  text-align: center;
}

.accent-btn {
  width: 100%;
  padding: 12px;
  background-color: #5856d6;
  color: white;
  border-radius: 8px;
  font-size: 16px;
  text-align: center;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-content {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.loading-text {
  font-size: 14px;
  color: #333;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 